<?php
namespace backend\controllers;

use Yii;
use yii\web\Controller;
use yii\helpers\ArrayHelper;
use backend\models\Goods;
use backend\models\FilesForm;
use backend\models\Files;
use backend\models\Category;
use backend\models\Article;
class GoodsController extends BaseController{
	public $nodeName = '商品管理';
	public $init_upload_image = '/common/uploads/system/upload.jpg';

	public function init(){
        parent::init();
	}

	public function actionLists(){
		$lists = Goods::find()->asArray()->all();
		return $this->render('lists', ['lists' => $lists]);
	}

	public function actionCreate(){
		$id = $this->request->get('id');

		if(!empty($id)){
			$goods = Goods::findOne($id);
			$goods->setScenario('update');
            $articleElder = ArrayHelper::getColumn(Article::find()->select('title')->asArray()->all(), 'title');
		}else{
			$goods = new Goods;
			$goods->setScenario('create');
            $articleElder = ArrayHelper::getColumn(Article::find()->select('title')->asArray()->all(), 'title');
		}

		if($this->request->isPost){
			if($goods && $goods->load($this->request->post())){
				if($goods->save()){
					$this->session->setFlash('success', '保存成功!');
					return $this->redirect(['/goods/lists']);
				}else{
					$this->session->setFlash('error', '保存失败!');
				}
			}else{
				$this->session('error', '???????!!!!!');
			}

		}

		$result = [
			'goods' => $goods,
			'pageTitle' => '创建商品',
            'articleElder' => $articleElder,
		];

		return $this->render('data-form', $result);
	}


	public function actionDel(){
        $id = yii::$app->request->get('id');

        if($id && !yii::$app->user->isGuest){
            $good = Goods::find()->where(['id' => $id])->one();
            if($good->delete()){
                $this->session->setFlash('success', '删除成功!');
            }
            $this->session->setFlash('error', '删除失败!');
        }else{
            $this->session->setFlash('error', '异常!');
        }

        $this->request(['/goods/lists']);
	}

	public function actionSearch(){
		Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
		$out = ['results' => ['id' => '', 'text' => '']];

		/*if (!$q) {
	        return $out;
	    }*/

	    $data = Goods::find()
	                ->select('id, name AS text')
	                ->asArray()
	                ->all();
	                
	    $out['results'] = array_values($data);

	    return $out;
	}
}